// 用户工具函数

/**
 * 获取用户凭据信息
 * @returns 用户凭据对象或null
 */
export const getUserCredentials = () => {
  try {
    const credentials = localStorage.getItem('userCredentials')
    if (credentials) {
      return JSON.parse(credentials)
    }
    return null
  } catch (error) {
    console.error('解析用户凭据失败:', error)
    return null
  }
}

/**
 * 获取用户名
 * @returns 用户名字符串
 */
export const getUsername = (): string => {
  // 优先从userCredentials获取
  const credentials = getUserCredentials()
  if (credentials && credentials.username) {
    return credentials.username
  }
  
  // 备用方案：从userInfo获取
  try {
    const userInfo = localStorage.getItem('userInfo')
    if (userInfo) {
      const parsedUserInfo = JSON.parse(userInfo)
      return parsedUserInfo.username || ''
    }
  } catch (error) {
    console.error('解析用户信息失败:', error)
  }
  
  return ''
}

/**
 * 获取用户头像
 * @returns 头像URL字符串或null
 */
export const getUserAvatar = (): string | null => {
  return localStorage.getItem('userAvatar')
}

/**
 * 检查用户是否已登录
 * @returns 是否已登录
 */
export const isUserLoggedIn = (): boolean => {
  const username = getUsername()
  const avatar = getUserAvatar()
  return !!(username || avatar)
}

/**
 * 获取用户完整信息
 * @returns 用户信息对象
 */
export const getUserInfo = () => {
  return {
    username: getUsername(),
    avatar: getUserAvatar(),
    isLoggedIn: isUserLoggedIn()
  }
}

/**
 * 清除用户信息
 */
export const clearUserInfo = () => {
  localStorage.removeItem('userCredentials')
  localStorage.removeItem('userInfo')
  localStorage.removeItem('userAvatar')
  localStorage.removeItem('userAvatarInfo')
}
